package com.example.ws.service.Impl;

import com.example.ws.service.IOnlineUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.websocket.Session;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Service
public class OnlineUserServiceImpl implements IOnlineUserService {
    private static final String ONLINE_USERS_KEY = "chat:online_users";
    private static final String SESSION = "chat:session";
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Override
    public void userLogin(String name) {
        Long result= redisTemplate.opsForSet().add(ONLINE_USERS_KEY,name);
        System.out.println("用户登录结果：" + result);
        if (Boolean.TRUE.equals(redisTemplate.hasKey(ONLINE_USERS_KEY))) {
            redisTemplate.expire(ONLINE_USERS_KEY, 1, TimeUnit.HOURS);
        }

    }

    @Override
    public void userLogout(String name) {
        Long res = redisTemplate.opsForSet().remove(ONLINE_USERS_KEY,name);
        System.out.println("用户退出结果：" + res);
    }

    @Override
    public Set<String> getOnlineUsers() {
        Set<String> onlineUsers = redisTemplate.opsForSet().members(ONLINE_USERS_KEY);
        System.out.println("在线用户：" + onlineUsers);
        return onlineUsers;
    }

    @Override
    public void storeSession(String name, Session session) {
        redisTemplate.opsForHash().put(SESSION,name,session.getId());
    }
}
